package com.cssw.fyzb.busi.api.task;

import com.cssw.fyzb.busi.convert.Converter;
import com.cssw.fyzb.core.model.vo.task.TaskExecVo;
import com.cssw.fyzb.busi.service.task.TaskService;
import com.cssw.fyzb.core.model.dodb.TaskExec;
import com.cssw.fyzb.core.util.DateUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.dbframe.plugin.activerecord.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author
 */
@Function(description = "任务执行记录", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户标识", required = true),
        @Parameter(name = "status", type = Type.String, description = "状态", required = true),
        @Parameter(name = "pageNumber", type = Type.Integer, description = "当前页，从1开始", required = true),
        @Parameter(name = "pageSize", type = Type.Integer, description = "页大小", required = true)
})
@Component
public class ListTaskExec implements Action {

    private final static Logger logger = LoggerFactory.getLogger(ListTaskExec.class);

    @Autowired
    private TaskService taskService;

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        String status = request.getString("status");
        Integer pageNumber = request.getInteger("pageNumber");
        Integer pageSize = request.getInteger("pageSize");

        try {
            Page<TaskExec> page = taskService.listTaskExec(userId, status, pageNumber, pageSize);

            List<TaskExecVo> list = ((Converter<List<TaskExec>, List<TaskExecVo>>) videos -> {
                List<TaskExecVo> vos = new ArrayList<>();
                videos.forEach((v) -> {
                    TaskExecVo vo = new TaskExecVo();
                    vo.setComplateTime(v.getComplateTime());
                    vo.setCreateTime(DateUtil.format(v.getCreateTime()));
                    vo.setDayValue(v.getDayValue());
                    vo.setExecId(v.getExecId());
                    vo.setInstId(v.getInstId());
                    vo.setTaskName(v.getTaskName());
                    vo.setUserId(v.getUserId());
                    vos.add(vo);
                });
                return vos;
            }).convert(page.getList());
            return Response.success().put("list", list).put("total", page.getTotalPage()).put("count", page.getTotalRow());
        } catch (Exception e) {
            logger.info("", e);
            return Response.fail("操作异常");
        }
    }
}
